<template>
  <view class="add-supplier">
    <!-- 表单内容 -->
    <scroll-view class="form-container" scroll-y>
      <form @submit="submitForm">
        <!-- 类型选择 -->
        <view class="form-section">
          <text class="section-title">类型选择</text>
          <view class="type-selector">
            <view class="type-item" :class="{ active: formData.type === 'company' }" @click="selectType('company')">
              <view class="type-icon">
                <uni-icons type="home" size="30" :color="formData.type === 'company' ? '#1890ff' : '#999'"></uni-icons>
              </view>
              <text class="type-text">经营主体</text>
            </view>
            <view class="type-item" :class="{ active: formData.type === 'person' }" @click="selectType('person')">
              <view class="type-icon">
                <uni-icons type="person" size="30" :color="formData.type === 'person' ? '#1890ff' : '#999'"></uni-icons>
              </view>
              <text class="type-text">自然人</text>
            </view>
          </view>
        </view>

        <!-- 证件上传 -->
        <view class="form-section">
          <text class="section-title">证件上传</text>
          <image-uploader
            ref="imageUploader"
            upload-type="supplierCertificate"
            upload-text="点击上传证件"
            upload-hint="请上传清晰的证件照片"
            :initial-image-url="formData.certificate"
            @upload-complete="handleUploadComplete"
          ></image-uploader>
          <view class="ocr-tips">
            <text class="tips-text">支持OCR自动识别证件信息，减少手动输入</text>
          </view>
        </view>

        <!-- 基础信息 -->
        <view class="form-section">
          <text class="section-title">基础信息</text>

          <view class="form-item">
            <text class="form-label required">供货者名称</text>
            <input class="form-input" v-model="formData.supplierName" :placeholder="formData.type === 'company' ? '请输入企业名称' : '请输入姓名'" />
          </view>

          <view class="form-item">
            <text class="form-label required">联系电话</text>
            <input class="form-input" v-model="formData.phone" type="number" placeholder="请输入11位手机号" maxlength="11" />
          </view>

          <view class="form-item" v-if="formData.type === 'company'">
            <text class="form-label">统一社会信用代码</text>
            <input class="form-input" v-model="formData.creditCode" placeholder="可通过证件识别自动填写" />
          </view>

          <view class="form-item" v-if="formData.type === 'person'">
            <text class="form-label">身份证号码</text>
            <input class="form-input" v-model="formData.idCard" placeholder="请输入18位身份证号码" maxlength="18" />
          </view>
        </view>

        <!-- 底部按钮 -->
        <view class="bottom-actions">
          <button class="cancel-btn" @click="cancelAdd">取消</button>
          <button class="save-btn" form-type="submit">保存</button>
        </view>
      </form>
    </scroll-view>
  </view>
</template>

<script>
import { addSupplier } from '@/api/system/supplier.js';
import ImageUploader from '@/components/image-uploader.vue';

export default {
  components: {
    ImageUploader,
  },
  data() {
    return {
      formData: {
        type: 'company', // company: 经营主体, person: 自然人
        supplierName: '',
        creditCode: '',
        idCard: '', // 身份证号码
        address: '',
        phone: '',
        certificate: '',
      },
    };
  },
  methods: {
    // 处理上传完成事件
    handleUploadComplete(url) {
      console.log('证件上传完成，URL:', url);
      this.formData.certificate = url;
    },

    // 选择类型
    selectType(type) {
      this.formData.type = type;
      if (type === 'person') {
        this.formData.creditCode = ''; // 清空统一社会信用代码
      } else {
        this.formData.idCard = ''; // 清空身份证号码
      }
    },

    // 清空上传的证件
    clearCertificate() {
      if (this.$refs.imageUploader) {
        this.$refs.imageUploader.clearImage();
      }
    },

    // 验证表单
    validateForm() {
      if (!this.formData.supplierName) {
        uni.showToast({
          title: this.formData.type === 'company' ? '请输入企业名称' : '请输入姓名',
          icon: 'none',
        });
        return false;
      }

      // if (this.formData.type === 'company' && !this.formData.creditCode) {
      //   uni.showToast({
      //     title: '请输入统一社会信用代码',
      //     icon: 'none',
      //   });
      //   return false;
      // }

      // if (this.formData.type === 'person' && !this.formData.idCard) {
      //   uni.showToast({
      //     title: '请输入身份证号码',
      //     icon: 'none',
      //   });
      //   return false;
      // }

      // 验证身份证号码格式
      // if (this.formData.type === 'person' && this.formData.idCard) {
      //   const idCardReg = /^[1-9]\d{5}(19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/;
      //   if (!idCardReg.test(this.formData.idCard)) {
      //     uni.showToast({
      //       title: '身份证号码格式不正确',
      //       icon: 'none',
      //     });
      //     return false;
      //   }
      // }

      if (!this.formData.phone) {
        uni.showToast({
          title: '请输入联系电话',
          icon: 'none',
        });
        return false;
      }

      if (!/^1[3-9]\d{9}$/.test(this.formData.phone)) {
        uni.showToast({
          title: '请输入正确的手机号',
          icon: 'none',
        });
        return false;
      }

      // 证件上传改为可选
      // if (!this.formData.certificate) {
      //   uni.showToast({
      //     title: '请上传证件',
      //     icon: 'none'
      //   })
      //   return false
      // }

      return true;
    },

    // 提交表单
    async submitForm() {
      if (!this.validateForm()) return;

      uni.showLoading({ title: '保存中...' });

      try {
        // 构建提交数据 - 修正字段名以匹配后端
        const submitData = {
          supplierType: this.formData.type === 'company' ? '1' : '0', // company->1(合作社), person->0(个人)
          supplierName: this.formData.supplierName,
          contactPhone: this.formData.phone, // 修正：phone -> contactPhone
          status: '0', // 默认正常状态
        };

        // 可选字段
        if (this.formData.type === 'company' && this.formData.creditCode) {
          submitData.businessLicense = this.formData.creditCode;
        }
        if (this.formData.type === 'person' && this.formData.idCard) {
          submitData.idCard = this.formData.idCard;
        }
        if (this.formData.address) {
          submitData.contactPerson = this.formData.address; // 临时使用contactPerson字段存储地址
        }
        if (this.formData.certificate) {
          submitData.qualificationFile = this.formData.certificate;
        }

        console.log('提交的供货商数据:', submitData);
        const response = await addSupplier(submitData);
        console.log('新增供货商响应:', response);

        uni.hideLoading();

        if (response.code === 200) {
          uni.showToast({
            title: '添加成功',
            icon: 'success',
          });

          // 返回列表页面
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        } else {
          uni.showToast({
            title: response.msg || '添加失败',
            icon: 'none',
          });
        }
      } catch (error) {
        uni.hideLoading();
        console.error('添加供货者失败:', error);

        uni.showToast({
          title: error,
          icon: 'none',
        });
      }
    },

    // 取消添加
    cancelAdd() {
      uni.showModal({
        title: '提示',
        content: '确定要取消添加供货者吗？',
        success: (res) => {
          if (res.confirm) {
            uni.navigateBack();
          }
        },
      });
    },
  },
};
</script>

<style scoped>
.add-supplier {
  background-color: #f5f5f5;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

/* 表单容器 */
.form-container {
  flex: 1;
  padding-bottom: 140rpx;
}

/* 表单区块 */
.form-section {
  background-color: #fff;
  margin: 20rpx;
  border-radius: 16rpx;
  padding: 30rpx;
}

.section-title {
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
  margin-bottom: 30rpx;
  display: block;
}

/* 类型选择 */
.type-selector {
  display: flex;
  gap: 30rpx;
}

.type-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40rpx 0;
  border: 2rpx solid #e8e8e8;
  border-radius: 16rpx;
  background-color: #fafafa;
  transition: all 0.3s;
}

.type-item.active {
  border-color: #1890ff;
  background-color: #e6f7ff;
}

.type-icon {
  margin-bottom: 16rpx;
}

.type-text {
  font-size: 30rpx;
  color: #333;
}

.type-item.active .type-text {
  color: #1890ff;
  font-weight: 500;
}

/* 表单项 */
.form-item {
  margin-bottom: 30rpx;
}

.form-item:last-child {
  margin-bottom: 0;
}

.form-label {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 16rpx;
  display: block;
}

.form-label.required::before {
  content: '*';
  color: #ff4d4f;
  margin-right: 8rpx;
}

.form-input {
  width: 100%;
  height: 88rpx;
  padding: 0 24rpx;
  background-color: #f5f5f5;
  border-radius: 12rpx;
  font-size: 30rpx;
  color: #333;
}

.form-input[disabled] {
  color: #999;
}

/* 证件上传 - 使用组件后不需要自定义样式 */

.ocr-tips {
  margin-top: 20rpx;
  padding: 20rpx;
  background-color: #f0f8ff;
  border-radius: 8rpx;
}

.tips-text {
  font-size: 24rpx;
  color: #1890ff;
}

/* 底部按钮 */
.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 20rpx 30rpx 40rpx;
  display: flex;
  gap: 30rpx;
  box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.05);
  z-index: 1;
}

.cancel-btn,
.save-btn {
  flex: 1;
  height: 80rpx;
  border-radius: 40rpx;
  font-size: 32rpx;
  font-weight: 500;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
}

.cancel-btn {
  background-color: #f5f5f5;
  color: #666;
}

.save-btn {
  background-color: #1890ff;
  color: #fff;
}
</style>
